package com.eascs.admin.o2o.user;

import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.controller.BaseViewController;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.assertion.util.AssertErrorUtils;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.cookie.CookieSpec;
import com.eascs.web.context.RequestContext;
import com.eascs.web.exception.RedirectException;
import com.eascs.web.p3p.P3pHeader;
import com.eascs.web.sso.SsoUserInterceptor;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sys.LoginLogEntity;
import com.eascs.workflow.common.service.sys.LoginConstant;
import com.eascs.workflow.common.service.sys.LoginLogDubboService;
import com.eascs.workflow.common.vo.ModelResult;

@Controller
public class SsoUserViewController extends BaseViewController {
	private static final Logger logger = LoggerFactory.getLogger(SsoUserViewController.class);

	@Reference
	LoginLogDubboService loginLogDubboService;

	@RequestMapping(value = "/o2o/sso/valid", method = RequestMethod.GET)
	@P3pHeader
	public String valid(ValidForm validForm) {
		AssertErrorUtils.assertNotNull(UserHolder.getUser(), "can't get user from UserHolder");
		// update VailIdCookie
		CookieSpec vailIdCookieSpec = SsoUserInterceptor.buildVailIdCookieSpec();
		vailIdCookieSpec.setValue(RequestContext.getRequestedSessionId());

		// build returnUrl
		String returnUrl = validForm.getReturnUrl();
		String fullServer = UrlUtil.getRequestFullServer(returnUrl);
		if (fullServer.indexOf("eascs.com") < 0) {
			returnUrl = UrlUtil.appendUrl(returnUrl, SsoUserInterceptor.PARAM_VALIDID, vailIdCookieSpec.getValue());
		}

		LoginLogEntity login = new LoginLogEntity();
		if (UserHolder.getUser() != null) {
			login.setLoginName(UserHolder.getUser().getAccount());
			login.setLoginCnName(UserHolder.getUser().getCname());
		}
		login.setLoginDate(new Date());
		login.setIp(RequestContext.getRemoteAddr());
		login.setLoginSource(LoginConstant.LOGIN_PC);
		login.setUseragent(RequestContext.getHeader("user-agent"));
		login.setLoginMarking(CookieSpec.build("u_id").getValue());
		login.setLoginType(LoginConstant.HM);
		login.setGeoInfo(null);
		login.setRemark("用户通过pc端登录系统");
		ModelResult<LoginLogEntity> model = loginLogDubboService.writeLog(login);
		if(!model.isSuccess()){
			logger.error("记录用户登录日志失败,errMsg:{}", model.getErrMsg());
		}
		
		logger.debug("valid to {}", returnUrl);
		throw new RedirectException(returnUrl);
	}
}
